package com.ilxqx.fierce.core;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

/**
 * 对象转换工厂
 *
 * @author Venus
 * @since 1.0.0
 */
@Component
public class Map2ObjConverterFactory implements ConverterFactory<Map<String, Object>, Object> {
    private static final Map<Class<?>, Converter<Map<String, Object>, Class<?>>> CONVERTER_MAP = new ConcurrentReferenceHashMap<>(512);

    /**
     * Get the converter to convert from S to target type T, where T is also an instance of R.
     *
     * @param targetType the target type to convert to
     * @return a converter from S to T
     */
    @NonNull
    @Override
    @SuppressWarnings("unchecked")
    public <T> Converter<Map<String, Object>, T> getConverter(@NonNull Class<T> targetType) {
        return (Converter<Map<String, Object>, T>) CONVERTER_MAP.computeIfAbsent(targetType, key -> new Map2ObjConverter<>(targetType));
    }
}
